module Redmine
  class ExcelUtil
    #生成文本样式,统一表格样式
    def self.get_sheet_style(wb)
      style = wb.styles
      style.fonts.first.sz = 12
      header = style.add_style alignment: {horizontal: :center}, b: true, sz: 14, bg_color: "0066CC", fg_color: "FF"
      content_time = style.add_style alignment: {horizontal: :center}, format_code: "yyyy-mm-dd HH:MM:ss", sz:12
      wrap = style.add_style alignment: {wrap_text: true}
      content = style.add_style alignment: {horizontal: :center}, sz:12
      vertical = style.add_style alignment: {vertical: :center, horizontal: :center}
      error = style.add_style sz: 14, bg_color: "db3b21"
      content2 = style.add_style alignment: {horizontal: :left}, sz:12
      content3 = style.add_style alignment: {horizontal: :right}, sz:12
      # linear-gradient(#f0a273, #f6f6f6);
      {
          header: header,
          content_time: content_time,
          wrap: wrap,
          content: content,
          error: error,
          vertical: vertical,
          content_left: content2,
          content_right: content3
      }
    end

    #生成excel,保存到文件中并且返回文件路径
    def self.generate
      pack = Axlsx::Package.new
      pack.use_autowidth = true
      pack.workbook do |wb|
        yield wb if block_given?
      end
      pack.use_shared_strings = true
      file_path = File.join("#{Rails.root}/tmp/excel", 'plans', DateTime.now.strftime('%Y%m%d'))
      FileUtils.mkdir_p file_path unless File.exists?(file_path)
      file_path = File.join(file_path, "#{Digest::MD5.hexdigest(Time.now.to_s)}.xlsx")
      File.delete(file_path) if File.exist?(file_path)
      pack.serialize file_path
      file_path
    end
  end
end